<?php
namespace app\admin\controller;

use app\admin\Controller;
use think\Db;

class User extends Controller
{
    //会员列表
    public function index()
    {
        $where = array();
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (isset($post['status']) && $post['status'] != 2) {
                $where['status'] = $post['status'];
            }
            switch ($post['userType']) {
                case '0':
                    $where['agent'] = 0;
                    break;
                case '1':
                    $where['agent'] = ['gt', 0];
                    break;
            }
            if (!empty($post['keyword'])) {
                switch ($post['type']) {
                    case '1':
                        $where['username'] = $post['keyword'];
                        break;
                    case '2':
                        $where['id'] = $post['keyword'];
                        break;
                    case '3':
                        $where['mobile'] = $post['keyword'];
                        break;
                    case '4':
                        $where['email'] = $post['keyword'];
                        break;
                }
            }
            $this->assign('post', json_encode($post));
        }
        $users = Db::name('user')->where($where)->paginate(10);
        $this->assign('users', $users);
        return $this->fetch();
    }

    //编辑用户
    public function edit($id = 0)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (!empty($post['password'])) {
                $post['password'] = md5(md5($post['id'] . $post['password']));
            } else {
                unset($post['password']);
            }
            $result = Db::name('user')->update($post);
            $return = ['status' => 0, 'msg' => '操作失败！'];
            if ($result) {
                $return['status'] = 1;
                $return['msg']    = "修改用户成功！";
            } else {
                $return['msg'] = "修改用户失败...";
            }
            exit(json_encode($return));
        }
        if ($id > 0) {
            $user = Db::name('user')->find($id);
            unset($user['password']);
            $this->assign('user', json_encode($user));
            return $this->fetch();
        }

    }

    //代理审核列表
    public function examine()
    {
        if ($this->request->isPost()) {
            $post  = $this->request->post();
            $apply = Db::name('apply_agent')->find($post['id']);
            if (!$apply) {
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            if ($post['action']) {
                //审核成功
                if ($apply['status'] == 1) {
                    return json(['success' => 0, 'msg' => '已经是审核成功状态']);
                }
                //修改状态
                if (Db::name('apply_agent')->update(['id' => $apply['id'], 'status' => 1])) {
                    //设置代理
                    if(!Db::name('user')->where('id',$apply['user_id'])->setField('agent',1)){
                        return json(['success' => 0, 'msg' => '操作失败，请重试']);
                    }
                    //发送站内信
                    send_message($apply['user_id'], '恭喜您的代理申请审核通过');
                    //成功代理奖励
                    $config  = config('currency');
                    $message = '成为代理奖励';
                    if ($config['agentRecharge'] > 0) {
                        inc_money($apply['user_id'], $apply['username'], 'recharge', $config['agentRecharge'], $message, 19);
                    }
                    if ($config['agentGame'] > 0) {
                        inc_money($apply['user_id'], $apply['username'], 'game', $config['agentGame'], $message, 19);
                    }
                    if ($config['agentShopping'] > 0) {
                        inc_money($apply['user_id'], $apply['username'], 'shopping', $config['agentShopping'], $message, 19);
                    }
                    return json(['success' => 1, 'msg' => '操作成功']);
                }
            } else {
                //审核失败
                if ($apply['status'] == 2) {
                    return json(['success' => 0, 'msg' => '已经是审核失败状态']);
                }
                //修改状态
                if (Db::name('apply_agent')->update(['id' => $apply['id'], 'status' => 2])) {
                    //发送站内信
                    send_message($apply['user_id'], '很抱歉，您的代理申请审核未通过，失败原因：' . $post['note']);
                    return json(['success' => 1, 'msg' => '操作成功']);
                }
            }
            return json(['success' => 1, 'msg' => '操作失败']);
        } else {
            $list = Db::name('apply_agent')->paginate(10);
            $this->assign('list', $list);
            return $this->fetch();
        }
    }

    //用户冻结
    public function lock($id = 0, $status = 0)
    {
        //冻结一个用户
        if ($id > 0) {
            if ($status) {
                if (Db::name('user')->where('id', $id)->setField('status', 1)) {
                    $this->success('恢复成功');
                }
            } else {
                if (Db::name('user')->where('id', $id)->setField('status', 0)) {
                    $this->success('冻结成功');
                }
            }
        }
        //批量冻结用户
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids/a');
            if (Db::name('user')->where('id', 'in', $ids)->setField('status', 0)) {
                $this->success('批量冻结成功');
            }
        }
        $this->success('操作失败！');
    }

    //推荐结构
    public function tree()
    {
        $data = Db::name('user')->field('id,username AS name,invite')->select();
        $tree = $this->getUserTree($data);
        $this->assign('tree', json_encode($tree));
        return $this->fetch();
    }

    //获取用户树
    private function getUserTree($list, $pk = 'id', $pid = 'invite', $child = 'children', $root = 0)
    {
        $tree = [];
        if (is_array($list)) {
            $refer = [];
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           = &$refer[$parentId];
                        $parent[$child][] = &$list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    //主账户列表
    public function main()
    {
        if ($this->request->isPost()) {
            if ($this->request->post('username')) {
                $where['username'] = $this->request->post('username');
            }
        }
        $list = Db::name('main_account')->where($where)->order('id desc')->paginate(10);
        $this->assign('list', $list);
        $this->assign('post', json_encode($this->request->post()));
        return $this->fetch();
    }

    //子账户列表
    public function son()
    {
        if ($this->request->isPost()) {
            if ($this->request->post('username')) {
                $where['username'] = $this->request->post('username');
            }
        }
        $list = Db::name('son_account')->where($where)->order('id desc')->paginate(10);
        $this->assign('list', $list);
        $this->assign('post', json_encode($this->request->post()));
        return $this->fetch();
    }

    //分红记录
    public function abonus()
    {
        $type = ['abonus' => '分红基金', 'charity' => '慈善基金'];
        $list = Db::name('fund_record')->order('id desc')->paginate(10);
        $this->assign('list', $list);
        $this->assign('type', $type);
        return $this->fetch();
    }

    //挂售记录
    public function sell()
    {
        if ($this->request->isPost()) {
            if ($this->request->post('username')) {
                $where['username'] = $this->request->post('username');
            }
        }
        $list = Db::name('sell')->where($where)->order('id desc')->paginate(10);
        $this->assign('list', $list);
        $this->assign('post', json_encode($this->request->post()));
        return $this->fetch();
    }

    //延时
    public function delayed()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['id']) || empty($post['hour'])) {
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            $timeout = time() + $post['hour'] * 3600;
            if (Db::name('sell')->where('id', $post['id'])->setField('timeout', $timeout)) {
                return json(['success' => 1, 'msg' => '延长超时成功']);
            }
            return json(['success' => 0, 'msg' => '延长超时失败']);
        }
    }

    //重置
    public function reset()
    {
        if ($this->request->isPost()) {
            $id  = $this->request->post('id');
            $row = Db::name('sell')->find($id);
            if (!$row || $row['status'] == 4) {
                return json(['success' => 0, 'msg' => '非法操作']);
            }
            //扣违约金
            $config = config('currency');
            if ($config['cancelPunish'] > 0) {
                $agent = Db::name('user')->find($row['agent_id']);
                dec_money($agent['id'], $agent['username'], 'money', $config['cancelPunish'], '管理员重置接单ID：' . $row['id'] . ' 扣除违约金', 13);
            }
            //补偿挂售人
            if ($config['cancelReward'] > 0) {
                inc_money($row['user_id'], $row['username'], 'money', $config['cancelReward'], '管理员重置挂单ID：' . $row['id'] . ' 获得系统补偿', 14);
            }
            //重新挂售
            $result = Db::name('sell')->update([
                'id'       => $row['id'],
                'agent_id' => 0,
                'time'     => time(),
                'timeout'  => 0,
                'status'   => 0,
            ]);
            if (!$result) {
                return json(['success' => 0, 'msg' => '重置挂单失败']);
            }
            return json(['success' => 1, 'msg' => '重置挂单成功']);
        }
    }

    //提现列表
    public function withdraw()
    {
        if ($this->request->isPost()) {
            if ($this->request->post('username')) {
                $where['username'] = $this->request->post('username');
            }
        }
        $list = Db::name('withdraw')->where($where)->order('id desc')->paginate(10);
        $this->assign('list', $list);
        $this->assign('post', json_encode($this->request->post()));
        return $this->fetch();
    }

    //确认提现
    public function confirmPay()
    {
        if ($this->request->isPost()) {
            $currency = config('currency');
            $post     = $this->request->post();
            $row      = Db::name('withdraw')->find(intval($post['id']));
            if (!$row) {
                return json(['status' => 0, 'msg' => '非法操作']);
            }
            //成功
            if ($post['status'] == 1) {
                if ($row['status'] == 1) {
                    return json(['status' => 0, 'msg' => '该提现申请已经是成功状态']);
                }
                $result = Db::name('withdraw')->update([
                    'id'       => $row['id'],
                    'status'   => 1,
                    'pay_time' => time(),
                ]);
                if (!$result) {
                    return json(['status' => 0, 'msg' => '操作失败']);
                }
                if ($row['shopping']) {
                    $message = "申请ID： {$row['id']} 提现成功，{$currency['shopping']} 到账";
                    inc_money($row['user_id'], $row['username'], 'shopping', $row['shopping'], $message, 7);
                }
                return json(['status' => 1, 'msg' => '操作成功']);
            }
            //失败
            if ($post['status'] == 2) {
                if ($row['status'] == 2) {
                    return json(['status' => 0, 'msg' => '该提现申请已经是失败状态']);
                }
                $result = Db::name('withdraw')->update([
                    'id'     => $row['id'],
                    'status' => 2,
                    'note'   => $post['note'],
                ]);
                if (!$result) {
                    return json(['status' => 0, 'msg' => '操作失败']);
                }
                //提现退款
                $message = "申请ID： {$row['id']} 提现失败，{$currency['money']} 退款";
                inc_money($row['user_id'], $row['username'], 'money', $row['money'], $message, 7);
                return json(['status' => 1, 'msg' => '操作成功']);
            }
        }
    }
}
